<template>
  <div class="page-render-wrap" v-if="lowCodeRender">
    <a-form
      ref="formRef"
      :model="lowCodeRender?.model"
      :layout="lowCodeRender!.globalConfig!.labelPosition"
      :size="lowCodeRender!.globalConfig!.size"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <template
        tag="div"
        v-for="(element, index) in lowCodeRender?.root?.items"
        :key="index"
      >
        <div v-if="element && element.key">
          <render-parse
            :element="element"
            :key="element?.key"
            :index="index"
            :parent="lowCodeRender?.root?.items"
          >
            <!-- 关键点：把当前组件的所有插槽透传下去 -->
            <template v-for="(_, name) in $slots" :key="name" #[name]="data">
              <slot :name="name" v-bind="data" />
            </template>
          </render-parse>
        </div>
      </template>
    </a-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, provide, ref } from "vue";
import { createLowCode } from "@/components/low-code/core/index";

export default defineComponent({
  name: "page-render",
  props: {
    pageJson: {
      type: Object,
      required: true,
    },
    afterGetSchemas: {
      type: Function,
      required: false,
    },
    afterGetTables: {
      type: Function,
      required: false,
    },
  },
  setup(props, { expose }) {
    const lowCodeRender = createLowCode({
      ...props.pageJson,
      isDesigner: false,
    });

    const formRef = ref(null);
    lowCodeRender.formController.setFormRefs("Root", formRef);
    const setColumns = (key: any, ColumnGroup: Map<string, any>) => {
      lowCodeRender.tableController.setColumns(key, ColumnGroup);
    };

    if (props.afterGetTables instanceof Function) {
      props.afterGetTables && props.afterGetTables(setColumns);
    } else {
      console.warn("afterGetTables 必须是函数");
    }
    if (props.afterGetSchemas instanceof Function) {
      const setSchemas = (schemas: Map<string, any>) => {
        lowCodeRender.formController.setSchemas(undefined, schemas);
      };
      props.afterGetSchemas && props.afterGetSchemas(setSchemas);
    } else {
      console.warn("afterGetSchemas 必须是函数");
    }

    // const rootCompnent: Component = lowCodeRender.dataCenter[
    //   lowCodeRender!.root!.key
    // ] as Component;

    provide("getLowCodeInstance", () => {
      return lowCodeRender;
    });

    const setDataSource = (key: string,data: any[])=>{
      lowCodeRender.tableController.setDataSource(key, data);
    }

    // 使用 expose 暴露给外部
    expose({
      lowCodeRender,
      setDataSource
    });
    return {
      lowCodeRender,
      formRef,
    };
  },
});
</script>

<style scoped>
.page-render-wrap {
}
</style>
